import numpy as np
import pandas as pd
import pymysql

class MySqlUtils(object):
    def __init__(self):
        self.conn = pymysql.connect(
            host='localhost',
            user='root',
            password='root',
            database='scenic',
            port=3306,
            charset='utf8',
            cursorclass=pymysql.cursors.DictCursor
        )
    
    def get_data(self):
        cursor = self.conn.cursor()
        sql = """
            SELECT 
            t.tourist_agency_name, rel.id_no, 
            LEFT(rel.id_no, 2) as province_code, 
            DAYOFWEEK(gate.create_time) as weekend, 
            CAST(SUBSTRING(rel.id_no, 7, 4)as UNSIGNED) as birth_year 
            from scenic.ticket_order_user_rel rel 
            JOIN scenic.ticket_order t on t.id = rel.order_id
            JOIN scenic.order_user_gate_rel gate on gate.ticket_rel_id = rel.id
            WHERE t.tourist_agency_name != '' AND t.pay_time != ''
        """
        cursor.execute(sql)
        data = cursor.fetchall()
        cursor.close()
        self.conn.close()
        
        if not data:
            print("没有查询到数据")
            return
        
        df = pd.DataFrame(data)
        
        df['non_weekend'] = df['weekend'].apply(lambda x: 1 if x not in [1, 7] else 0)
        
        df['valid_id'] = df['id_no'].apply(
            lambda x: 1 if pd.notna(x) and str(x).strip() != '' and len(str(x).strip()) >= 18 else 0
        )
        
        df['eldery_flag'] = df.apply(
            lambda x: 1 if x['valid_id'] and (2025 - x['birth_year']) >= 60 else 
                      0 if x['valid_id'] else np.nan, 
            axis=1
        )
        
        df['out_province_flag'] = df.apply(
            lambda x: 1 if x['valid_id'] and str(x['province_code']).strip() != '44' else 
                      0 if x['valid_id'] else np.nan, 
            axis=1
        )
        
        result = df.groupby('tourist_agency_name').agg(
            total_visitors=('id_no', 'count'), 
            valid_visitors=('valid_id', 'sum'), 
            non_weekend_visitors=('non_weekend', 'sum'), 
            eldery_visitors=('eldery_flag', 'sum'), 
            out_province_visitors=('out_province_flag', 'sum')  
        ).round(3)
        
        result['elderly_ratio'] = result['eldery_visitors'] / result['valid_visitors'].replace(0, np.nan)
        result['non_weekend_ratio'] = result['non_weekend_visitors'] / result['total_visitors'].replace(0, np.nan)
        result['out_province_ratio'] = result['out_province_visitors'] / result['valid_visitors'].replace(0, np.nan)
        
        result = result.round(3).reset_index()
        
        print("统计结果：")
        print(result)
        result.to_csv('scenic_data.csv', index=False, encoding='utf-8-sig')  

if __name__ == '__main__':
    mysql_utils = MySqlUtils()
    mysql_utils.get_data()
